package com.yc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yc.entity.Attendance;
import com.yc.mapper.AttendanceMapper;
import com.yc.vo.AttendanceHistory;
import com.yc.enums.ClassTime;
import com.yc.exception.CustomException;
import com.yc.vo.Result;
import com.yc.vo.StudentAttendanceRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.yc.entity.AttendanceRecords;
import com.yc.mapper.AttendanceRecordsMapper;
import com.yc.service.AttendanceRecordsService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 考勤详情表;(attendance_records)表服务实现类
 * @author zxy mqm
 * @date : 2023-6-28
 */
@Api("考勤详情表实现类")
@Service
public class AttendanceRecordsServiceImpl implements AttendanceRecordsService{
    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;
    @Autowired
    private AttendanceMapper attendanceMapper;

    /**
     *  计算学生个人得分
     * @author zxy
     * @param stuid 学生id
     * @return 该状态的次数
     */
    @ApiOperation("计算学生的个人得分")
    public int finalscore(String stuid) {
        int latecount = attendanceRecordsMapper.StatusCount(stuid, 3);// 查询迟到的次数
        int Earlycount = attendanceRecordsMapper.StatusCount(stuid,4);// 查询早退的次数
        int truancycount = attendanceRecordsMapper.StatusCount(stuid,5);// 查询旷课的次数
        int subtractscore = 0;// 要减去的分数（初始为0
        int finalscore = 50;// 最终分数（默认50分满分
        // 计算要扣除的分数
        subtractscore = (latecount+Earlycount)/3 + truancycount;//迟到和早退满三次扣一分 旷课直接扣一分
        finalscore = finalscore - subtractscore;
        return finalscore;// 返回最终分数
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public AttendanceRecords queryById(Integer id){
        return attendanceRecordsMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param attendanceHistory 筛选条件
     * @param current 当前页码
     * @param size  每页大小
     * @return
     */
    @Override
    public Page<AttendanceRecords> paginQuery(AttendanceHistory attendanceHistory, long current, long size){
        Integer id = attendanceMapper.selectOne(new LambdaQueryWrapper<Attendance>().
                eq(Attendance::getScheduleid, attendanceHistory.getSid())).getId();
        //1. 构建动态查询条件
        LambdaQueryWrapper<AttendanceRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttendanceRecords::getAttid,id);
        //2. 执行分页查询
        Page<AttendanceRecords> pagin = new Page<>(current , size , true);
        IPage<AttendanceRecords> selectResult = attendanceRecordsMapper.selectByPage(pagin , queryWrapper);
        pagin.setPages(selectResult.getPages());
        pagin.setTotal(selectResult.getTotal());
        pagin.setRecords(selectResult.getRecords());
        //3. 返回结果
        return pagin;
    }

    /**
     * 新增数据
     *
     * @param attendanceRecords 实例对象
     * @return 实例对象
     */
    @Override
    public boolean insert(List<AttendanceRecords> attendanceRecords,String id){
        return attendanceRecordsMapper.insertBatch(attendanceRecords,id);
    }

    /**
     * 更新数据
     *
     * @param attendanceRecords 实例对象
     * @return 实例对象
     */
    @Override
    public AttendanceRecords update(AttendanceRecords attendanceRecords){
        //1. 根据条件动态更新
        LambdaUpdateChainWrapper<AttendanceRecords> chainWrapper = new LambdaUpdateChainWrapper<AttendanceRecords>(attendanceRecordsMapper);
        if(StrUtil.isNotBlank(attendanceRecords.getStuid())){
            chainWrapper.eq(AttendanceRecords::getStuid, attendanceRecords.getStuid());
        }
        //2. 设置主键，并更新
        chainWrapper.set(AttendanceRecords::getId, attendanceRecords.getId());
        boolean ret = chainWrapper.update();
        //3. 更新成功了，查询最最对象返回
        if(ret){
            return queryById(attendanceRecords.getId());
        }else{
            return attendanceRecords;
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id){
        int total = attendanceRecordsMapper.deleteById(id);
        return total > 0;
    }

    /**
     * 统计当前学年的旷课、请假、早退情况
     * @return
     */
    @Override
    public Map<String, Object> selectAllAttendanceByStudent(String stuid, String beginDate, String endDate){
        return attendanceRecordsMapper.selectAllAttendanceByStudent(stuid, beginDate, endDate);
    }
    /**
     * 获取当天的考勤记录
     * @param stuid 学生学号
     * @param date 当天日期
     * @return 当天的考勤情况
     */
    public Map<String,List<StudentAttendanceRecord>> selectAttendanceByStuidAndDate(@Param("stuid") String stuid,@Param("date") String date){
        List<StudentAttendanceRecord> records = attendanceRecordsMapper.selectAttendanceByStuidAndDate(stuid, date);
        Map<String, List<StudentAttendanceRecord>> result = new HashMap<>();
        String date1; // 月日 07-19
        int hour; // 小时
        int minute; // 分钟
        int cop = 0;
        for (StudentAttendanceRecord record : records) {
            date1 = record.getDate().split(" ")[0];
            hour = Integer.valueOf(record.getDate().split(" ")[1].substring(0, 2));
            minute = Integer.valueOf(record.getDate().split(" ")[1].substring(3, 5));
            if (result.containsKey(date1)){
                result.get(date1).add(record);
            }else {
                List<StudentAttendanceRecord> tmpList = new ArrayList<>();
                tmpList.add(record);
                result.put(date1, tmpList);
            }
            date1 = date1.substring(5);
            // 上课具体时间
            cop = hour * 60 + minute;
            if (record.getClasstime().length() > 1){
                if (cop >= ClassTime.COURSE1_BEGIN && cop<= ClassTime.COURSE1_END){
                    date1 += " 上午 第一节";
                }else if (cop>= ClassTime.COURSE2_BEGIN && cop<= ClassTime.COURSE2_END){
                    date1 += " 上午 第二节";
                }else if (cop>= ClassTime.COURSE3_BEGIN && cop<= ClassTime.COURSE3_END){
                    date1 += " 下午 第一节";
                }else if (cop>= ClassTime.COURSE4_BEGIN && cop<= ClassTime.COURSE4_END){
                    date1 += " 下午 第二节";
                }else if (cop>= ClassTime.COURSE5_BEGIN && cop<= ClassTime.COURSE5_END){
                    date1 += " 晚上 第一节";
                }else {
                    date1 += " 加课";
                }
            }else {
                if (cop >= ClassTime.COURSE1_1_BEGIN && cop <= ClassTime.COURSE1_1_END){
                    date1 += " 上午 第一小节";
                }else if (cop >= ClassTime.COURSE1_2_BEGIN && cop <= ClassTime.COURSE1_2_END){
                    date1 += " 上午 第二小节";
                }else if (cop >= ClassTime.COURSE2_1_BEGIN && cop <= ClassTime.COURSE2_1_END){
                    date1 += " 上午 第三小节";
                }else if (cop >= ClassTime.COURSE2_2_BEGIN && cop <= ClassTime.COURSE2_2_END){
                    date1 += " 上午 第四小节";
                }else if (cop >= ClassTime.COURSE3_1_BEGIN && cop <= ClassTime.COURSE3_1_END){
                    date1 += " 下午 第一小节";
                }else if (cop >= ClassTime.COURSE3_2_BEGIN && cop <= ClassTime.COURSE3_2_END){
                    date1 += " 下午 第二小节";
                }else if (cop >= ClassTime.COURSE4_1_BEGIN && cop <= ClassTime.COURSE4_1_END){
                    date1 += " 下午 第三小节";
                }else if (cop >= ClassTime.COURSE4_2_BEGIN && cop <= ClassTime.COURSE4_2_END){
                    date1 += " 下午 第四小节";
                }else if (cop >= ClassTime.COURSE5_1_BEGIN && cop <= ClassTime.COURSE5_1_END){
                    date1 += " 晚上 第一小节";
                }else if (cop >= ClassTime.COURSE5_2_BEGIN && cop <= ClassTime.COURSE5_2_END){
                    date1 += " 晚上 第二小节";
                }else {
                    date1 += " 加课";
                }
            }

            record.setDate(date1);
        }
        return result;
    }

    /**
     * 获取当月的考勤记录
     * @param stuid 学生学号
     * @param date 当月日期
     * @return 学生当月的考勤记录
     */
    @Override
    public Map<String, List<StudentAttendanceRecord>> selectMonthAttendanceByStuidAndDate(String stuid,String date){
        List<StudentAttendanceRecord> records = attendanceRecordsMapper.selectMonthAttendanceByStuidAndDate(stuid, date);
        Map<String, List<StudentAttendanceRecord>> result = new HashMap<>();
        String date1;
        for (StudentAttendanceRecord record : records) {
            date1 = record.getDate().split(" ")[0];
            if (result.containsKey(date1)){
                result.get(date1).add(record);
            }else {
                List<StudentAttendanceRecord> tmpList = new ArrayList<>();
                tmpList.add(record);
                result.put(date1, tmpList);
            }
        }
        return result;
    }

    /**
     * 通过学号获取该学生当月的上课状态
     * @param stuid 学生学号
     * @param date  当月日期
     * @return  学生当月的上课状态
     */
    @Override
    public Map<String, List<StudentAttendanceRecord>> selectMonthStatusByStuidAndDate(@Param("stuid") String stuid, @Param("date") String date){
        // 将日期相同的放入 一个数组中
        List<StudentAttendanceRecord> records = attendanceRecordsMapper.selectMonthStatusByStuidAndDate(stuid, date);
        Map<String, List<StudentAttendanceRecord>> result = new HashMap<>();
        String date1;
        for (StudentAttendanceRecord record : records) {
            date1 = record.getDate().split(" ")[0];
            if (result.containsKey(date1)){
                result.get(date1).add(record);
            }else {
                List<StudentAttendanceRecord> tmpList = new ArrayList<>();
                tmpList.add(record);
                result.put(date1, tmpList);
            }
        }
        return result;
    }

    /**
     *@Description 查询指定班级的所有考勤信息
     *@Return
     *@Author dm
     *@Date Created in 2023/7/26 19:34
     **/
    @Override
    public Result queryHistory(AttendanceHistory attendanceHistory, Integer pageNum, Integer pageSize){
        //数据
        List<AttendanceHistory> attendanceHistories = null;
        //数据总数
        int count = 0;
        //1.分页参数
        long current = (pageNum - 1) * pageSize;
        long size = pageSize;
        attendanceHistories = attendanceRecordsMapper.queryPage(attendanceHistory, current, size);
        count = attendanceRecordsMapper.countHistory(attendanceHistory);
        Map<String, Object> data = new HashMap<>();
        /*1已到
         * 2请假
         * 3迟到
         * 4早退
         * 5旷课*/
        int[] statusNums = {attendanceRecordsMapper.queryStatusNums(attendanceHistory, 1)
                ,attendanceRecordsMapper.queryStatusNums(attendanceHistory, 2)
                ,attendanceRecordsMapper.queryStatusNums(attendanceHistory, 3)
                ,attendanceRecordsMapper.queryStatusNums(attendanceHistory, 4)
                ,attendanceRecordsMapper.queryStatusNums(attendanceHistory, 5)};
        attendanceHistories.forEach(his -> {
            switch (his.getStatus()) {
                case "1":
                    his.setStatus("已到");
                    break;
                case "2":
                    his.setStatus("请假");
                    his.setStyle("qingjie-row");
                    break;
                case "3":
                    his.setStatus("迟到");
                    his.setStyle("chidao-row");
                    break;
                case "4":
                    his.setStatus("早退");
                    his.setStyle("zaotuo-row");
                    break;
                case "5":
                    his.setStatus("旷课");
                    his.setStyle("kuangke-row");
                    break;
            }
        });
        data.put("list", attendanceHistories);
        data.put("total", count);
        data.put("statusNums", statusNums);
        return Result.success(data);
    }

    /**
     * 批量添加学生手动考勤记录
     * @param attendanceRecordsList 学生考勤记录集合
     * @param username 老师工号
     */
    @Transactional
    @Override
    public void addAttendanceRecords(List<AttendanceRecords> attendanceRecordsList, String username){
        int res = attendanceRecordsMapper.addAttendanceRecords(attendanceRecordsList, username);
        if (res <= 0){
            throw new CustomException("0","考勤失败!");
        }
    }

    /**
     * 批量修改学生手动考勤记录
     * @param attendanceRecordsList 学生考勤记录集合
     * @param username 老师工号
     * @return 成功 0失败
     */
    @Override
    public int modifyAttendanceRecords(List<AttendanceRecords> attendanceRecordsList, String username){
        int res = attendanceRecordsMapper.modifyAttendanceRecords(attendanceRecordsList, username);
        return res;
    }

    /**
     * 统计每个月的考勤记录
     * @param stuid 学生学号
     * @param status 考勤状态
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPerMonthAttendance(String stuid, String status, String beginDate, String endDate){
        List<Map<String, Object>> res = attendanceRecordsMapper.selectPerMonthAttendance(stuid, status, beginDate, endDate);
        if (res.size() <= 0){
            throw new CustomException("0", "本年份暂无数据");
        }
        return res;
    }

    /**
     * 查询每学年的起始时间 和 结束时间
     * @param date 学年起始时间
     * @return 起始时间 和 结束时间
     */
    @Override
    public List<String> selectNowSchoolYear(Integer date){
        List<String> dates = attendanceRecordsMapper.selectNowSchoolYear(date);
        if (dates.size() <= 0){
            throw new CustomException("0", "暂无本学年信息");
        }
        return dates;
    }
}
